package edu.sias.ims.student.controller;

import edu.sias.ims.common.annotation.Log;
import edu.sias.ims.common.enums.BusinessType;
import edu.sias.ims.common.utils.poi.ExcelUtil;
import edu.sias.ims.student.domain.dto.ExportDto;
import edu.sias.ims.student.service.ExportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api("导出数据接口")
@RestController
@RequestMapping("/export/export")
public class ExportController {

    @Autowired
    private ExportService exportService;


    @ApiOperation("导出数据表")
    @PreAuthorize("@ss.hasPermi('export:export:export')")
    @Log(title = "导出数据表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExportDto exportDto) throws IllegalAccessException {
        List<ExportDto> list = exportService.selectByTargat(exportDto);
        Map<String, Object> FileMap = objectToMap(exportDto);
        String[] array = FileMap.entrySet().stream()
                .filter(entry -> entry.getValue() == null)
                .map(Map.Entry::getKey)
                .toArray(String[]::new);

        ExcelUtil<ExportDto> util = new ExcelUtil<ExportDto>(ExportDto.class);
        util.hideColumn(array);
        util.exportExcel(response, list, "导出数据");
    }


    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> result = new HashMap<>();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            result.put(field.getName(), field.get(obj));
        }
        return result;
    }
}

